﻿using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using RestSharp;
using RestSharp.Interceptors;

namespace ATSSDK.Internal;

internal class ATSInterceptor(ILogger logger) : Interceptor
{
    public override ValueTask BeforeRequest(RestRequest request, CancellationToken cancellationToken)
    {
        logger.LogDebug("Request: {request}, parameters: {content}", request.Resource, request.Parameters.ToJson());

        return base.BeforeRequest(request, cancellationToken);
    }

    public override ValueTask AfterRequest(RestResponse response, CancellationToken cancellationToken)
    {
        logger.LogDebug("Response: {request} {statusCode}, content: {content}", response.ResponseUri, response.StatusCode, response.Content);

        return base.AfterRequest(response, cancellationToken);
    }

    public override ValueTask BeforeDeserialization(RestResponse response, CancellationToken cancellationToken)
    {
        if (!response.IsSuccessStatusCode)
        {
            throw new ATSException(response.Content ?? response.StatusCode.ToString());
        }
        return base.BeforeDeserialization(response, cancellationToken);
    }
}